package cn.edu.niit.server.web.rest;

import cn.edu.niit.server.domain.ContentInfo;
import cn.edu.niit.server.domain.UserAccount;
import cn.edu.niit.server.repository.ContentInfoRepository;
import cn.edu.niit.server.repository.UserAccountRepository;
import cn.edu.niit.server.security.SecurityUtils;
import cn.edu.niit.server.service.ContentInfoService;
import cn.edu.niit.server.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.xml.ws.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link cn.edu.niit.server.domain.ContentInfo}.
 */
@RestController
@RequestMapping("/api")
public class ContentInfoResource {

    private final Logger log = LoggerFactory.getLogger(ContentInfoResource.class);

    private static final String ENTITY_NAME = "contentInfo";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final ContentInfoService contentInfoService;

    private final ContentInfoRepository contentInfoRepository;

    private final UserAccountRepository userAccountRepository;

    public ContentInfoResource(
        ContentInfoService contentInfoService,
        ContentInfoRepository contentInfoRepository,
        UserAccountRepository userAccountRepository
    ) {
        this.contentInfoService = contentInfoService;
        this.contentInfoRepository = contentInfoRepository;
        this.userAccountRepository = userAccountRepository;
    }

    /**
     * {@code POST  /content-infos} : Create a new contentInfo.
     *
     * @param contentInfo the contentInfo to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new contentInfo, or with status {@code 400 (Bad Request)} if the contentInfo has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/content-infos")
    public ResponseEntity<ContentInfo> createContentInfo(@RequestBody ContentInfo contentInfo) throws URISyntaxException {
        log.debug("REST request to save ContentInfo : {}", contentInfo);
        if (contentInfo.getId() != null) {
            throw new BadRequestAlertException("A new contentInfo cannot already have an ID", ENTITY_NAME, "idexists");
        }
        //在保存发生之前，对海报数据对象进行默认值处理
        contentInfo.setContentTime(ZonedDateTime.now());
        contentInfo.setContentFavorateCount(0l);
        contentInfo.setContentPraiseCount(0l);

        //当前登录用户
        String login = SecurityUtils.getCurrentUserLogin().get();
        UserAccount userAccount = this.userAccountRepository.findByLogin(login);
        contentInfo.setAccount(userAccount);
        if (userAccount != null) {
            contentInfo.setContentAuthor(userAccount.getNickname());
        }

        ContentInfo result = contentInfoService.save(contentInfo);
        return ResponseEntity
            .created(new URI("/api/content-infos/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /content-infos/:id} : Updates an existing contentInfo.
     *
     * @param id          the id of the contentInfo to save.
     * @param contentInfo the contentInfo to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated contentInfo,
     * or with status {@code 400 (Bad Request)} if the contentInfo is not valid,
     * or with status {@code 500 (Internal Server Error)} if the contentInfo couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/content-infos/{id}")
    public ResponseEntity<ContentInfo> updateContentInfo(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody ContentInfo contentInfo
    ) throws URISyntaxException {
        log.debug("REST request to update ContentInfo : {}, {}", id, contentInfo);
        if (contentInfo.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, contentInfo.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!contentInfoRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        ContentInfo result = contentInfoService.save(contentInfo);
        return ResponseEntity
            .ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, contentInfo.getId().toString()))
            .body(result);
    }

    /**
     * {@code PATCH  /content-infos/:id} : Partial updates given fields of an existing contentInfo, field will ignore if it is null
     *
     * @param id          the id of the contentInfo to save.
     * @param contentInfo the contentInfo to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated contentInfo,
     * or with status {@code 400 (Bad Request)} if the contentInfo is not valid,
     * or with status {@code 404 (Not Found)} if the contentInfo is not found,
     * or with status {@code 500 (Internal Server Error)} if the contentInfo couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/content-infos/{id}", consumes = "application/merge-patch+json")
    public ResponseEntity<ContentInfo> partialUpdateContentInfo(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody ContentInfo contentInfo
    ) throws URISyntaxException {
        log.debug("REST request to partial update ContentInfo partially : {}, {}", id, contentInfo);
        if (contentInfo.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, contentInfo.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!contentInfoRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<ContentInfo> result = contentInfoService.partialUpdate(contentInfo);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, contentInfo.getId().toString())
        );
    }

    /**
     * {@code GET  /content-infos} : get all the contentInfos.
     *
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of contentInfos in body.
     */
    @GetMapping("/content-infos")
    public ResponseEntity<List<ContentInfo>> getAllContentInfos(Pageable pageable) {
        log.debug("REST request to get a page of ContentInfos");
        Page<ContentInfo> page = contentInfoService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /content-infos/:id} : get the "id" contentInfo.
     *
     * @param id the id of the contentInfo to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the contentInfo, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/content-infos/{id}")
    public ResponseEntity<ContentInfo> getContentInfo(@PathVariable Long id) {
        log.debug("REST request to get ContentInfo : {}", id);
        Optional<ContentInfo> contentInfo = contentInfoService.findOne(id);
        return ResponseUtil.wrapOrNotFound(contentInfo);
    }

    /**
     * {@code DELETE  /content-infos/:id} : delete the "id" contentInfo.
     *
     * @param id the id of the contentInfo to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/content-infos/{id}")
    public ResponseEntity<Void> deleteContentInfo(@PathVariable Long id) {
        log.debug("REST request to delete ContentInfo : {}", id);
        contentInfoService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }

    @GetMapping("/content-infos/type")
    public ResponseEntity getContentByType(Long typeId, Integer page, Integer size) {
        Page<ContentInfo> result = contentInfoService.findByType(typeId, page, size);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/content-infos/mine")
    public ResponseEntity getMyContent(
        @RequestParam(required = false, defaultValue = "0") Integer page,
        @RequestParam(required = false, defaultValue = "15") Integer size
    ) {
        //获取登录名
        Optional<String> loginOptional = SecurityUtils.getCurrentUserLogin();
        if (loginOptional.isPresent()) {
            String login = loginOptional.get();
            if (login.equals("anonymousUser")) {
                return ResponseEntity.status(401).body("请先登录");
            }
            Page<ContentInfo> result = this.contentInfoService.getMyContent(login, page, size);

            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.status(401).body("请先登录");
        }
    }
}
